<script setup lang="tsx">
import { ContentWrap } from '@/components/ContentWrap'
import { Search } from '@/components/Search'
import { Dialog } from '@/components/Dialog'
import { Form, FormSchema } from '@/components/Form'
import { useForm } from '@/hooks/web/useForm'
import { Table, TableColumn } from '@/components/Table'
import { pick } from 'lodash-es'
import { ElButton, ElMessage, ElMessageBox } from 'element-plus'
import { useValidator } from '@/hooks/web/useValidator'
import md5 from 'md5'

import { useSearch } from '@/hooks/web/useSearch'
import { useTable } from '@/hooks/web/useTable'
import { ref, reactive, unref, computed } from 'vue'
import {
  getUserPartnerApi,
  getAllPartnerApi,
  saveUserPartnerApi,
  DeleteUserPartnerApi,
  getUserCodeApi
} from '@/api/user'
import { ResetPasswordApi } from '@/api/login'
import { useUserStore } from '@/store/modules/user'
import { useI18n } from '@/hooks/web/useI18n'
const { t } = useI18n()

const userStore = useUserStore()

const allPartner = ref<any>()
const getAllPartner = async () => {
  const { data } = await getAllPartnerApi()
  allPartner.value = data
}
// Search
const { searchRegister, searchMethods } = useSearch()
const { getFormData: getSearchFormData } = searchMethods
const searchSchema = reactive<FormSchema[]>([
  {
    field: 'userName',
    label: '用户名',
    component: 'Input',
    componentProps: {
      onKeyup: (event) => {
        if (event.keyCode === 13) {
          getList()
        }
      }
    }
  }
])
// Form
const { formRegister, formMethods } = useForm()
const { getElFormExpose, setValues, getFormData } = formMethods
const { required } = useValidator()
const formData = ref<any>({})
const superiorsParams = reactive({
  parentId: '',
  parentName: ''
})
const schema = computed<FormSchema[]>(() => [
  {
    field: 'realName',
    label: '名称',
    component: 'Input',
    formItemProps: {
      rules: [required()]
    }
  },
  {
    field: 'userName',
    label: '用户名',
    component: 'Input',
    formItemProps: {
      rules: [required()]
    }
  },
  {
    field: 'password',
    label: '密码',
    component: 'Input',
    componentProps: {
      type: 'password'
    },
    formItemProps: {
      rules: [required()]
    },
    remove: isEdit.value
  },

  {
    field: 'mail',
    label: '邮箱',
    component: 'Input',
    formItemProps: {
      rules: [required()]
    }
  },
  {
    field: 'phone',
    label: '联系方式',
    component: 'Input',
    formItemProps: {
      rules: [required()]
    }
  },
  {
    field: 'userCode',
    label: '用户ID',
    component: 'Input',
    componentProps: {
      disabled: isEdit.value,
      onBlur: async () => {
        const data = await getFormData()
        if (data.userCode) {
          const res = await getUserCodeApi({ code: data.userCode })
          setValues({ parentName: res.data.code })
          superiorsParams.parentId = res.data.id
          superiorsParams.parentName = res.data.userName
        }
      }
    },
    formItemProps: {
      rules: [required()]
    }
  },
  {
    field: 'parentName',
    label: '上级名称',
    component: 'Input'
  },
  {
    field: 'proportion',
    label: '分成比例(%)',
    component: 'InputNumber',
    componentProps: {
      max: 100,
      min: 0
    },
    formItemProps: {
      rules: [required()]
    },
    remove: userStore.getUserInfo.ratioAuth !== 1
  },
  {
    field: 'versionType',
    label: '版本类型',
    component: 'Select',
    componentProps: {
      options: [
        {
          label: '正常版本',
          value: 1
        },
        {
          label: '特殊版本',
          value: 2
        }
      ]
    },
    formItemProps: {
      rules: [required()]
    },
    remove: userStore.getUserInfo.ratioAuth !== 1
  },
  {
    field: 'ratioAuth',
    label: '比例权限',
    component: 'Select',
    componentProps: {
      options: [
        {
          label: '开启',
          value: 1
        },
        {
          label: '关闭',
          value: 2
        }
      ],
      onChange: (val: any) => {
        if (val === 2) {
          setValues({
            proportion: 100
          })
        }
      }
    },
    formItemProps: {
      rules: [required()]
    },
    remove: userStore.getUserInfo.ratioAuth !== 1
  }
])
//Table
const columns = reactive<TableColumn[]>([
  {
    field: 'index',
    label: t('tableDemo.index'),
    type: 'index'
  },
  {
    field: 'userName',
    label: '名称'
  },
  {
    field: 'userCode',
    label: '用户ID'
  },
  {
    field: 'parentName',
    label: '上级名称'
  },
  {
    field: 'realName',
    label: '用户名'
  },
  {
    field: 'proportion',
    label: '分成比例'
  },

  {
    field: 'createTime',
    label: '创建时间'
  },
  {
    field: 'createTime',
    label: '操作',
    slots: {
      default: ({ row }) => {
        return (
          <div>
            <ElButton
              type="primary"
              size="small"
              onClick={() => {
                onOpenDialog(row)
              }}
            >
              编辑
            </ElButton>
            <ElButton
              type="primary"
              size="small"
              onClick={() => {
                eidtPasswordDialog(row)
              }}
            >
              修改密码
            </ElButton>
            <ElButton
              type="danger"
              size="small"
              onClick={() => {
                onDelete(row)
              }}
            >
              删除
            </ElButton>
          </div>
        )
      }
    }
  }
])
const { tableRegister, tableState, tableMethods } = useTable({
  fetchDataApi: async () => {
    const { currentPage, pageSize } = tableState
    const searchFormData = await getSearchFormData()
    const { data, count } = await getUserPartnerApi({
      pageNo: unref(currentPage),
      pageSize: unref(pageSize),
      appId: userStore.getAppId,
      ...searchFormData
    })
    return {
      list: data,
      total: count
    }
  }
})
const { loading, dataList, total, currentPage, pageSize } = tableState
const { getList } = tableMethods
// 打开弹窗
const visible = ref(false)
const isEdit = ref(false)
const disabled = ref(false)
const title = computed(() => (isEdit.value ? '编辑' : '新增'))
const onOpenDialog = (row: any) => {
  visible.value = true
  if (row) {
    // 编辑
    isEdit.value = true

    setValues(
      pick(row, [
        'id',
        'code',
        'realName',
        'userName',
        'password',
        'mail',
        'phone',
        'userCode',
        'proxyLink',
        'proportion',
        'versionType',
        'ratioAuth',
        'parentName'
      ])
    )
  } else {
    // 新增
    isEdit.value = false
    getAllPartner()
  }
}
//
const eidtPasswordDialog = (row: any) => {
  ElMessageBox.prompt('请输入密码', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    inputType: 'password',
    inputPattern: /\S/,
    inputErrorMessage: '密码不能为空'
  })
    .then(async ({ value }) => {
      await ResetPasswordApi({
        userId: row.userId,
        newPwd: md5(value).toUpperCase()
      })
      ElMessage.success('修改成功')
    })
    .catch(() => {})
}
// 立即提交
const onFormSubmit = async () => {
  const elFormExpose = await getElFormExpose()
  console.log(elFormExpose?.validate(), '????')

  elFormExpose?.validate(async (isValid: any) => {
    if (!isValid) {
      ElMessage.warning('请填写完整信息')
      return
    } else {
      disabled.value = true
      const formData = await getFormData()

      const { code }: any = await saveUserPartnerApi({
        ...formData,
        parentId: superiorsParams.parentId,
        parentName: superiorsParams.parentName,
        recordId: userStore.getAppId,
        password: formData.password ? md5(formData.password).toUpperCase() : null
      })
      if (code == 0) {
        visible.value = false
        ElMessage.success('操作成功！')
        getList()
      } else {
        disabled.value = false
      }
    }
  })
}
const onDelete = (row) => {
  ElMessageBox.confirm('确定删除该记录吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    await DeleteUserPartnerApi({ id: row.id })
    ElMessage.success('删除成功')
    getList()
  })
}
// 重置
const onReset = async () => {
  const elFormExpose = await getElFormExpose()
  elFormExpose?.resetFields()
}
</script>

<template>
  <ContentWrap title="添加合伙人">
    <Search :schema="searchSchema" @search="getList" @reset="getList" @register="searchRegister" />
    <div class="flex justify-end mb-[16px]">
      <ElButton type="primary" @click="onOpenDialog(null)">
        <template #icon>
          <Icon :size="20" icon="material-symbols:add" />
        </template>
        新增
      </ElButton>
    </div>

    <Table
      v-model:pageSize="pageSize"
      v-model:currentPage="currentPage"
      :columns="columns"
      :data="dataList"
      row-key="id"
      :loading="loading"
      sortable
      headerAlign="center"
      align="center"
      :pagination="{
        total: total
      }"
      @register="tableRegister"
    />
    <Dialog v-model="visible" :title="title">
      <Form
        class="w-[400px] ml-[auto] mr-[auto]"
        :schema="schema"
        :model="formData"
        :isCol="false"
        @register="formRegister"
      />
      <template #footer>
        <div class="text-center mb-[16px]">
          <BaseButton v-if="!isEdit" @click="onReset">重置</BaseButton>
          <BaseButton type="primary" :disabeld="disabled" debounce @click="onFormSubmit"
            >立即提交</BaseButton
          >
        </div>
      </template>
    </Dialog>
  </ContentWrap>
</template>
